"""
验证 HiAgent 配置是否正确从环境变量读取
"""
import os
import sys

# 添加项目路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

# 加载 .env 文件
try:
    from dotenv import load_dotenv
    env_path = os.path.join(project_root, '.env')
    if os.path.exists(env_path):
        load_dotenv(env_path)
        print(f"Loaded .env from: {env_path}\n")
    else:
        print(f"Warning: .env file not found at {env_path}\n")
except ImportError:
    print("Warning: python-dotenv not installed, skipping .env loading\n")

from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig


def verify_config():
    """验证配置是否正确"""
    print("=" * 60)
    print("HiAgent 配置验证")
    print("=" * 60)

    # 检查必需的配置项
    required_configs = {
        'HOST': HiAgentConfig.HOST,
        'ACCESS_KEY': HiAgentConfig.ACCESS_KEY,
        'SECRET_KEY': HiAgentConfig.SECRET_KEY,
        'ACCOUNT_ID': HiAgentConfig.ACCOUNT_ID,
        'DEFAULT_WORKSPACE_ID': HiAgentConfig.DEFAULT_WORKSPACE_ID,
        'DEFAULT_MODEL_ID': HiAgentConfig.DEFAULT_MODEL_ID,
        'DEFAULT_EMBEDDING_MODEL_ID': HiAgentConfig.DEFAULT_EMBEDDING_MODEL_ID,
    }

    # 检查环境变量
    env_vars = {
        'HIAGENT_HOST': os.getenv('HIAGENT_HOST'),
        'HIAGENT_ACCESS_KEY': os.getenv('HIAGENT_ACCESS_KEY'),
        'HIAGENT_SECRET_KEY': os.getenv('HIAGENT_SECRET_KEY'),
        'HIAGENT_ACCOUNT_ID': os.getenv('HIAGENT_ACCOUNT_ID'),
        'HIAGENT_WORKSPACE_ID': os.getenv('HIAGENT_WORKSPACE_ID'),
        'HIAGENT_DEFAULT_MODEL_ID': os.getenv('HIAGENT_DEFAULT_MODEL_ID'),
        'HIAGENT_DEFAULT_EMBEDDING_MODEL_ID': os.getenv('HIAGENT_DEFAULT_EMBEDDING_MODEL_ID'),
    }

    print("\n1. 环境变量检查:")
    print("-" * 60)
    missing_vars = []
    for var_name, var_value in env_vars.items():
        if var_value:
            # 对敏感信息进行脱敏显示
            if 'KEY' in var_name or 'SECRET' in var_name:
                display_value = var_value[:10] + "..." if len(var_value) > 10 else "***"
            else:
                display_value = var_value
            print(f"[OK] {var_name}: {display_value}")
        else:
            print(f"[MISS] {var_name}: NOT SET")
            missing_vars.append(var_name)

    print("\n2. 配置类属性检查:")
    print("-" * 60)
    missing_configs = []
    for config_name, config_value in required_configs.items():
        if config_value:
            # 对敏感信息进行脱敏显示
            if 'KEY' in config_name or 'SECRET' in config_name:
                display_value = config_value[:10] + "..." if len(config_value) > 10 else "***"
            else:
                display_value = config_value
            print(f"[OK] {config_name}: {display_value}")
        else:
            print(f"[MISS] {config_name}: NOT SET")
            missing_configs.append(config_name)

    print("\n3. 其他配置:")
    print("-" * 60)
    print(f"   BASE_URL: {HiAgentConfig.get_base_url()}")
    print(f"   VERSION: {HiAgentConfig.VERSION}")
    print(f"   SERVICE: {HiAgentConfig.SERVICE}")
    print(f"   REGION: {HiAgentConfig.REGION}")
    print(f"   REQUEST_TIMEOUT: {HiAgentConfig.REQUEST_TIMEOUT}s")
    print(f"   MAX_RETRIES: {HiAgentConfig.MAX_RETRIES}")
    print(f"   DEFAULT_PAGE_SIZE: {HiAgentConfig.DEFAULT_PAGE_SIZE}")
    print(f"   MAX_PAGE_SIZE: {HiAgentConfig.MAX_PAGE_SIZE}")

    print("\n" + "=" * 60)

    # 验证结果
    if missing_vars:
        print(f"[WARNING] The following environment variables are not set:")
        for var in missing_vars:
            print(f"   - {var}")
        print(f"\nPlease set these variables in .env file")
        return False

    if missing_configs:
        print(f"[ERROR] The following configs are not set:")
        for config in missing_configs:
            print(f"   - {config}")
        return False

    print("[SUCCESS] All configs are set correctly!")
    return True


def test_config_usage():
    """测试配置是否可用"""
    print("\n" + "=" * 60)
    print("配置使用测试")
    print("=" * 60)

    try:
        from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient

        print("\n正在测试 API 客户端初始化...")
        client = HiAgentAPIClient()
        print(f"[OK] API client initialized successfully")
        print(f"   Base URL: {client.config.get_base_url()}")
        print(f"   Workspace ID: {client.config.DEFAULT_WORKSPACE_ID[:20]}...")

        return True
    except Exception as e:
        print(f"[ERROR] API client initialization failed: {str(e)}")
        return False


if __name__ == "__main__":
    print("\n开始验证 HiAgent 配置...")

    # 验证配置
    config_ok = verify_config()

    # 测试配置使用
    if config_ok:
        usage_ok = test_config_usage()

        if usage_ok:
            print("\n" + "=" * 60)
            print("[SUCCESS] All checks passed!")
            print("=" * 60)
            sys.exit(0)

    print("\n" + "=" * 60)
    print("[WARNING] Config check not fully passed, please check above issues")
    print("=" * 60)
    sys.exit(1)
